#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <ao/ao.h>
#include <string.h>

struct playlist{
	FILE *file2play;
	int lrcfd;
	struct playlist *next;
};

struct playlist *create_playlist(int argc,char *argv[])
{
	struct playlist *head,*tail;
	char *ptr2lrcfile,*ptr2dot;
	int lrcfd;

	head=(struct playlist *)malloc(sizeof(struct playlist));
	tail=head;
	tail->file2play=NULL;
	tail->lrcfd=-1;
	for(;*argv!=NULL;argv++){
		tail->file2play=fopen(*argv,"r");

		if(tail->file2play==NULL)
			continue;

		//ptr2lrcfile=(char *)malloc(sizeof(**argv));
		ptr2lrcfile=(char *)malloc(100);
		strcpy(ptr2lrcfile,*argv);
		ptr2dot= strrchr(ptr2lrcfile,'.');
		ptr2dot[1]='l';
		ptr2dot[2]='r';
		ptr2dot[3]='c';

		if((lrcfd=open(ptr2lrcfile,O_RDONLY))==-1)
			continue;
		tail->lrcfd=lrcfd;

		tail->next=(struct playlist *)malloc(sizeof(struct playlist));
		tail=tail->next;
		tail->file2play=NULL;
		tail->lrcfd=-1;
		tail->next=NULL;
	
	}

	return head;
}
int 
main(int argc, char *argv[])
{
	FILE  *file2play;
	int lrcfd,result;
	/*  ao */

	ao_initialize();
	int default_driver;   
	default_driver = ao_default_driver_id();

	struct playlist *pl;
	pl=create_playlist(argc,argv);

	/*ready to play*/

	pid_t pid;
	do{
		if((pid=fork())<0){
			fprintf(stderr,"fork error \n");
			exit(9);
		}
		if(pid==0){
			if(pl->lrcfd!=-1)
				lrc(pl->lrcfd);
			else
				exit(9);
		}else{
			if(pl->file2play!=NULL){
				result=mp3_play(default_driver,pl->file2play);
//				printf("%d \n",result);
				if(result!=0)
				result=ogg_play(default_driver,pl->file2play);

			}else{
				exit(9);
			}
		}
	pl=pl->next;
	}while(pl!=NULL);

       /* -- Close and shutdown -- */
	ao_shutdown();

       return 0;
}
